package com.beeway.blackgoose.activity;

import android.content.Intent;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSONObject;
import com.beeway.blackgoose.BaseApp;
import com.beeway.blackgoose.R;
import com.beeway.blackgoose.bean.UserLoginEntry;
import com.beeway.blackgoose.bean.UserLoginInfo;
import com.beeway.blackgoose.constants.Config;
import com.beeway.blackgoose.fragment.UserFragment;
import com.beeway.blackgoose.utils.ProgressUtils;
import com.beeway.blackgoose.utils.Utils;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.HttpHandler;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lidroid.xutils.view.annotation.event.OnClick;

public class LoginActivity extends AppCompatActivity implements View.OnClickListener {
    @ViewInject(R.id.login_brack_tv)
    private TextView blackTv;
    @ViewInject(R.id.login_forget_tv)
    private TextView forgetTv;
    @ViewInject(R.id.login_register_tv)
    private TextView registerTv;
    @ViewInject(R.id.login_username_edt)
    private EditText userNameEdt;
    @ViewInject(R.id.login_userpwd_edt)
    private EditText userpwdEdt;
    @ViewInject(R.id.login_enter_btn)
    private TextView enterBtn;
    @ViewInject(R.id.login_qq_img)
    private ImageView QQImg;
    @ViewInject(R.id.login_wechat_img)
    private ImageView wechatImg;
    @ViewInject(R.id.login_rember_cb)
    private CheckBox savePasswold;
    private SharedPreferences sp;
    private SharedPreferences.Editor editor;
    private Boolean isRemeber;
    private HttpUtils utils;
    private HttpHandler<String> handler;
    private boolean isLoginOk; //判断是否登录成功
    private String name;
    private String pwd;
    private OnUserScuccessListener listener;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        ViewUtils.inject(this);
        initView();
    }

    private void initView() {
        utils = new HttpUtils();
        blackTv.setOnClickListener(this);
        rememberUserPwd();
    }

    @OnClick({R.id.login_forget_tv, R.id.login_register_tv, R.id.login_qq_img, R.id.login_wechat_img, R.id.login_rember_cb, R.id.login_enter_btn})
    private void OnClick(View v) {
        name = userNameEdt.getText().toString();
        pwd = userpwdEdt.getText().toString();
        switch (v.getId()) {
            case R.id.login_register_tv: //注册
                startActivity(new Intent(this, RegisterActivity.class).putExtra(Config.COUPON_TYPE, Config.REGISTER_TYPE));
                break;
            case R.id.login_rember_cb: //记住密码

                break;
            case R.id.login_qq_img://qq登录
                break;
            case R.id.login_wechat_img: //微信登录
                break;
            case R.id.login_forget_tv: //忘记密码
                startActivity(new Intent(this, RegisterActivity.class).putExtra(Config.COUPON_TYPE, Config.FORGET_TYPE));
                break;
            case R.id.login_enter_btn://登录
                if (name != null && !name.equals("") && pwd != null && !pwd.equals("")) {
                    userLogin(name, pwd, Config.ACCOUT_TYPE_PHONE);


                } else {
                    Utils.getToastMessage("请输入用户名和密码");
                }
                break;
        }
        Utils.getAnimIn(this);
    }

    //保存密码和用户
    public void savePwd(String name, String pwd) {
        editor = sp.edit();
        if (savePasswold.isChecked()) {
            editor.putString("name", name);
            editor.putString("pwd", pwd);
            editor.putBoolean("isremeber", true);
        } else {
            editor.clear();
        }
        editor.commit();
    }

    //由于检测是否是选中状态类显示是 用户 密码
    public void rememberUserPwd() {
        sp = getSharedPreferences("savepsdfile", MODE_PRIVATE);
        isRemeber = sp.getBoolean("isremeber", false);
        if (isRemeber) {
            String name = sp.getString("name", "");
            String pwd = sp.getString("pwd", "");
            userNameEdt.setText(name);
            userpwdEdt.setText(pwd);
            savePasswold.setChecked(true);
        }
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        Utils.getAnimOut(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (handler != null) {
            handler.cancel();
        }
    }

    //用户登录服务器的请求
    public void userLogin(final String number, final String userPwd, String type) {
        handler = utils.send(HttpRequest.HttpMethod.POST, Config.USER_LOGIN_URL, Config.getUserLoginParams(number, userPwd, type), new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                String result = responseInfo.result;
                if (result != null) {
                    UserLoginEntry entry = JSONObject.parseObject(result, UserLoginEntry.class);
                    if (entry != null && !TextUtils.isEmpty(entry.getResult())) {
                        if (entry.getResult().equals(Config.STATE_SUCESS)) { //登录成功
                            Utils.getToastMessage("登录成功，正在获取用户信息..." + entry.getData().getConsumer_account());
                            if (listener != null) {
                                listener.setOnUserScuccessListener(entry.getData());
                            }
                            savePwd(number, userPwd);  //登录成功才进行保存
                            Intent intent = new Intent();
                            intent.putExtra("info", entry.getData());
                            setResult(10, intent);
                            isLoginOk = true;
                            finish();
                        } else if (entry.getResult().equals(Config.STATE_FAIL)) { //登录失败
                            String failMsg = entry.getMsg();
                            Utils.getToastMessage(failMsg);
                            isLoginOk = false;
                        }
                    }
                }
            }

            @Override
            public void onFailure(HttpException e, String s) {
                Utils.getToastMessage("网络异常");
                isLoginOk = false;
            }
        });

    }

    public interface OnUserScuccessListener {
        void setOnUserScuccessListener(UserLoginInfo info);
    }

    @Override
    public void onClick(View v) {
        onBackPressed();
    }

}
